package com.firmboy.lock;

import org.junit.Test;

/**
 * 手写死锁
 *
 * @author firmboy
 * @create 2018-05-04 下午4:52
 **/
public class DeadLock {



    @Test
    public void lockTest(){

        Object o1 = new Object();
        Object o2 = new Object();

        Thread t1 = new Thread(new T1(o1, o2));
        Thread t2 = new Thread((new T2(o1, o2)));

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }

    class T1 implements Runnable{


        Object o1;
        Object o2;

        public T1 (Object o1,Object o2){
            this.o1 = o1;
            this.o2 = o2;
        }

        @Override
        public void run() {

            synchronized (o1){
                System.out.println(Thread.currentThread().getName()+"o1资源被获取");
                synchronized (o2){
                    System.out.println(Thread.currentThread().getName()+"o2资源被获取");
                }
            }

        }


    }

    class T2 implements Runnable{

        Object o1;
        Object o2;

        public T2 (Object o1,Object o2){
            this.o1 = o1;
            this.o2 = o2;
        }


        @Override
        public void run() {
            synchronized (o2){
                System.out.println(Thread.currentThread().getName()+"o2资源被获取");
                synchronized (o1){
                    System.out.println(Thread.currentThread().getName()+"o1资源被获取");
                }
            }
        }
    }
}
